package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import feign.Feign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements EsManagerService {
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private SkuFeign skuFeign;
    //创建索引库结构
    @Override
    public void createIndexAndMapping() {
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);

    }
    //批量导入数据到索引库
    @Override
    public void importAll() {
        //远程调用skuFegin里的方法,不加入spuId条件进行查询，查询的是审核通过的所有sku
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if(skuList==null&&skuList.size()<0){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        String s = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfos = JSON.parseArray(s, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfos);

    }

    @Override
    public void importDataToESBySpuId(String spuId) {
        //远程调用skuFegin里的方法,加入spuId条件进行查询，查询的是审核通过的符合条件的sku
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if(skuList==null || skuList.size()<0){
            throw  new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //skulist转换为json
        String jsonSkuList = JSON.toJSONString(skuList);
        //将json转换为skuinfo
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonSkuList, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);

    }


    //根据souid删除es索引库中相关的sku数据
    @Override
    public void delDataBySpuId(String spuId) {
        //远程调用skuFegin里的方法,加入spuId条件进行查询，查询的是审核通过的符合条件的sku
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if(skuList==null || skuList.size()<0){
            throw  new RuntimeException("当前没有数据被查询到,无法删除索引库");
        }
        //循环删除
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
